package com.kim.rssreader.view;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;

import com.kim.rssreader.R;
import com.kim.rssreader.adapter.ContentImageAdapter;
import com.kim.rssreader.db.DBDAO;
import com.kim.rssreader.utils.DeviceUtils;
import com.kim.rssreader.utils.DrawableUtils;
import com.kim.rssreader.utils.SharedPreferencesUtils;
import com.kim.rssreader.utils.ValueConstant;

public class MyWebChromeClient extends WebChromeClient {

	private static final String LOG_TAG = "MyWebChromeClient";

	private Context context;

	private View dialogView;

	private TextView textView;

	private ViewPager viewPager;

	private LayoutInflater inflater;

	private int pageIndex;

	private String contentUrl;

	private List<String> imageUrls;

	private List<View> views;

	private DBDAO dbdao;

	private int lastIndex;

	public MyWebChromeClient(Context context, DBDAO dbdao, String contentUrl) {
		this.context = context;
		this.contentUrl = contentUrl;
		this.dbdao = dbdao;
		inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		imageUrls = dbdao.getContentImageUrls(contentUrl);
	}

	@Override
	public boolean onJsAlert(WebView view, String url, String message,
			JsResult result) {
		if (message != null && message.startsWith("page#")) {
			showOrignalPage(message.replace("page#", ""));
			result.cancel();
		} else {
			result.confirm();
			if (SharedPreferencesUtils.getValueBoolean(
					ValueConstant.PURETEXTMODE, ValueConstant.SETTINGSFILENAME,
					context)) {
				return true;
			}
			showImageDialog(message);
		}
		return true;
		// return super.onJsAlert(view, url, message, result);
	}

	/**
	 * 打开原文页面
	 * 
	 * @param url
	 */
	private void showOrignalPage(String url) {
		Uri uri = Uri.parse(url);
		Intent it = new Intent(Intent.ACTION_VIEW, uri);
		context.startActivity(it);
	}

	/**
	 * 浏览内容中图片
	 * 
	 * @param url
	 */
	private void showImageDialog(String url) {
		if (imageUrls == null || imageUrls.size() == 0) {
			imageUrls = dbdao.getContentImageUrls(contentUrl);
		}
		if (imageUrls == null) {
			return;
		}

		Log.i(LOG_TAG, "img url:" + url);

		dialogView = inflater.inflate(R.layout.rss_image_dialog, null);

		final Dialog dialog = new Dialog(this.context,
				R.style.Dialog_Fullscreen);
		dialog.setContentView(dialogView);

		Window dialogWindow = dialog.getWindow();
		WindowManager.LayoutParams p = dialog.getWindow().getAttributes();
		// 获取对话框当前的参数值
		// 高度设置为屏幕的1.0
		p.height = (int) (DeviceUtils.getDeviceHeight(context) * 1.0);
		// 宽度设置为屏幕的1.0
		p.width = (int) (DeviceUtils.getDeviceWidth(context) * 1.0);
		// 透明度
		p.alpha = 0.95f;
		dialogWindow.setAttributes(p);

		getDefaultPageIndex(url);
		initDrawable(contentUrl, url);
		makeDefaultView();

		textView = (TextView) dialogView.findViewById(R.id.txt_pageIndex);
		if (imageUrls != null) {
			textView.setText((pageIndex + 1) + " / " + imageUrls.size());
		}

		viewPager = (ViewPager) dialogView.findViewById(R.id.vp_content_img);
		if (imageUrls != null && imageUrls.size() > 0) {
			viewPager.setAdapter(new ContentImageAdapter(views));
			viewPager.setCurrentItem(pageIndex);
		}
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
				textView.setText((position + 1) + " / " + imageUrls.size());
				Drawable drawable = null;
				String imageUrl = imageUrls.get(position);
				if (imageUrl != null) {
					drawable = DrawableUtils.loadDrawableByNetUrl(imageUrl);
				}

				if (drawable != null) {
					ImageViewForDialog imageView = (ImageViewForDialog) views
							.get(position).findViewById(R.id.img_viewpageItem);
					imageView.setImageDrawable(drawable);
					imageView
							.setOnTouchListener(new ScaleDragableTouchListener(
									((Activity) context), imageView, drawable));
				}

				// // 将上一张浏览的图片还原
				// if (lastIndex != position) {
				// View view = views.get(position);
				// if (view != null) {
				// final ImageViewForDialog imageView = (ImageViewForDialog)
				// view
				// .findViewById(R.id.img_viewpageItem);
				// Drawable drawable = imageView.getDrawable();
				//
				// Rect outRect = new Rect();
				// view.getLocalVisibleRect(outRect);
				//
				// int horizontalModify = outRect.right - outRect.left;
				// int verticalModify = outRect.bottom - outRect.top;
				//
				// // 扩展到适屏大小
				// ImageScaleUtil.imageScale((Activity) context,
				// imageView, drawable, horizontalModify,
				// verticalModify);
				// outRect = null;
				// }
				// }
				// lastIndex = position;
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});

		// viewPager.setOnTouchListener(new View.OnTouchListener() {
		// @Override
		// public boolean onTouch(View v, MotionEvent event) {

		// if (MotionEvent.ACTION_MOVE == event.getAction()) {
		// View view = views.get(lastIndex);
		// ImageViewForDialog imageViewForDialog = null;
		// if (view != null) {
		// imageViewForDialog = (ImageViewForDialog) view
		// .findViewById(R.id.img_viewpageItem);
		// }
		// if (imageViewForDialog != null) {
		// return imageViewForDialog.dispatchTouchEvent(event);
		// }
		// }
		// return false;
		// }
		// });

		ImageView colseButton = (ImageView) dialogView
				.findViewById(R.id.img_close);
		colseButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		dialog.show();
	}

	private void makeDefaultView() {
		Drawable drawable = null;
		String imageUrl = imageUrls.get(pageIndex);
		if (imageUrl != null) {
			drawable = DrawableUtils.loadDrawableByNetUrl(imageUrl);
		}

		if (drawable != null) {
			ImageViewForDialog imageView = (ImageViewForDialog) views.get(
					pageIndex).findViewById(R.id.img_viewpageItem);
			imageView.setImageDrawable(drawable);
			imageView.setOnTouchListener(new ScaleDragableTouchListener(
					((Activity) context), imageView, drawable));
		}
	}

	private void initDrawable(String contentUrl, String url) {
		if (imageUrls != null && imageUrls.size() > 0) {
			views = new ArrayList<View>();
			for (int i = 0; i < imageUrls.size(); i++) {
				View pageItemView = inflater.inflate(
						R.layout.img_viewpage_item, null);
				views.add(pageItemView);
			}
		}

	}

	private void getDefaultPageIndex(String targetUrl) {
		if (imageUrls != null && imageUrls.size() > 0) {
			int index = -1;
			for (String imageUrl : imageUrls) {

				index++;
				if (imageUrl != null
						&& imageUrl.equals(targetUrl)
						|| (ValueConstant.LOCAL_PATH_SCHEMA + DrawableUtils
								.getImageSavePath(imageUrl)).equals(targetUrl)) {
					pageIndex = index;
					return;
				}
			}
		}
	}
}
